/*
 * 人人信用管理有限公司版权所有.
 * 
 * @Description:
 * 
 * @author: liyuliang
 * 
 * @date: 20 Apr 2017 10:44:16 am
 * 
 * 注意：本内容仅限于人人信用管理有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */

package com.rrx360.common.util;

import java.util.regex.Pattern;

public class PhoneNumberUtil {

  public static String trimToChina11(String s) {
    if (s == null) {
      return null;
    }
    s = s.trim().replace(" ", "");
    if (s.startsWith("+")) {
      s = s.substring(1);
    }
    if (s.startsWith("86")) {
      s = s.substring(2);
    }
    if (s.startsWith("0")) {
      s = s.substring(1);
    }
    if (!Validator.isChinaMobileNumber11(s)) {
      return null;
    }
    return s;
  }

  public static boolean chinaMobileEquals(String phoneNumber1, String phoneNumber2) {
    String pn1 = trimToChina11(phoneNumber1);
    String pn2 = trimToChina11(phoneNumber2);
    if (pn1 == null || pn2 == null) {
      return false;
    }
    return pn1.equals(pn2);

  }

  private static Pattern yidongPattern =
      Pattern.compile("^134[0-8]\\d{7}$|^(13[5-9]|147|15[0-27-9]|178|18[2-478])\\d{8}$");
  private static Pattern liantongPattern =
      Pattern.compile("^(13[0-2]|145|15[56]|176|18[56])\\d{8}$");
  private static Pattern dianxinPattern = Pattern.compile("^(133|153|173|177|18[019])\\d{8}$");

  public static MobileOperatorType getMobileOperatorType(String phoneNumber) {
    phoneNumber = trimToChina11(phoneNumber);
    if (phoneNumber == null) {
      return null;
    }
    boolean isYidong = yidongPattern.matcher(phoneNumber).matches();
    if (isYidong) {
      return MobileOperatorType.YIDONG;
    }
    boolean isLiantong = liantongPattern.matcher(phoneNumber).matches();
    if (isLiantong) {
      return MobileOperatorType.LIANTONG;
    }
    boolean isDianxin = dianxinPattern.matcher(phoneNumber).matches();
    if (isDianxin) {
      return MobileOperatorType.DIANXIN;
    }
    return null;
  }
}
